from contextlib import asynccontextmanager
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from fastapi import FastAPI
import logging

from ..server.mapper._UserChatHistoryMapper import _userChatHistoryMapper
from ..server.mapper._ChatHistoryCacheMapper import _chatHistoryCacheMapper
from .SyncCacheToDb import _sync_cache_to_db
from .Global import configuration

scheduler = AsyncIOScheduler()


@asynccontextmanager
async def lifespan(app: FastAPI):
    scheduler.start()
    scheduler.add_job(
        _sync_cache_to_db,
        "interval",
        seconds=configuration.update_time,
        kwargs={
            "db_mapper": _userChatHistoryMapper,
            "cache_mapper": _chatHistoryCacheMapper,
        },
    )
    logging.info("定时更新缓存任务启动成功...")
    yield
    scheduler.shutdown()
    logging.info("定时更新缓存任务停止成功...")
    await _sync_cache_to_db(
        db_mapper=_userChatHistoryMapper, cache_mapper=_chatHistoryCacheMapper
    )
    logging.info("FastAPI应用关闭...")
